<template>
  <el-container style="height: 100%; padding: 20px">
    <el-header style="line-height: 30px">
      <el-button
        type="primary"
        style="float: right; margin-left: 20px"
        size="large"
        @click="onExport"
        >Export<el-icon class="el-icon--right"><Upload /></el-icon
      ></el-button>
      <el-button
        type="warning"
        style="float: right"
        size="large"
        @click="onImport"
        >Import<el-icon class="el-icon--right"><Download /></el-icon
      ></el-button>
      Use Csv to batch import and export accounts! <br />
      Exporting will download a CSV file; importing will update existing
      accounts and add new accounts that do not exist using CSV (based on
      `name`).
    </el-header>
    <el-divider style="margin-top: 30px" />
    <el-upload
      ref="upload"
      class="upload-demo"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
      accept=".csv"
      drag
      :action="`${baseURL}api/csv/import`"
      :limit="1"
      :auto-upload="false"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        Drop file here or <em>click to import</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">limit 1 csv file, then click `import`</div>
      </template>
    </el-upload>
  </el-container>
</template>

<script>
import { ref } from "vue";
import axios from "axios";
import { genFileId, ElMessageBox } from "element-plus";

export default {
  setup() {
    const upload = ref(null);

    const onExport = () => {
      const link = document.createElement("a");
      link.href = `${axios.defaults.baseURL}api/csv/export`;
      link.download = "users.csv";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    };

    const onImport = () => {
      upload.value?.submit();
    };

    const handleSuccess = (response) => {
      ElMessageBox.alert(response.result);
    };

    const handleExceed = (files) => {
      upload.value?.clearFiles();
      const file = files[0];
      file.uid = genFileId();
      upload.value?.handleStart(file);
    };

    return {
      handleSuccess,
      upload,
      onExport,
      onImport,
      handleExceed,
      baseURL: axios.defaults.baseURL,
    };
  },
};
</script>
